import { ref, onMounted, onUnmounted } from 'vue'
import { message } from 'ant-design-vue'
import type { LifeEntity } from '@/api/types'

interface LifeEntityUpdateEvent {
  type: 'ENTITY_UPDATED' | 'ENTITY_CREATED' | 'ENTITY_DELETED' | 'STATUS_CHANGED'
  entityId: string
  entity?: LifeEntity
  oldStatus?: string
  newStatus?: string
}

export function useLifeEntityRealtime() {
  const isConnected = ref(false)
  const lastUpdate = ref<Date | null>(null)
  const updateEvents = ref<LifeEntityUpdateEvent[]>([])
  
  let ws: WebSocket | null = null
  let reconnectTimer: NodeJS.Timeout | null = null
  let heartbeatTimer: NodeJS.Timeout | null = null

  // 事件监听器
  const listeners = new Map<string, ((event: LifeEntityUpdateEvent) => void)[]>()

  // 连接WebSocket
  const connect = () => {
    try {
      const wsUrl = `${import.meta.env.VITE_WS_BASE_URL || 'ws://localhost:8080'}/ws/life-entities`
      ws = new WebSocket(wsUrl)

      ws.onopen = () => {
        console.log('Life entity WebSocket connected')
        isConnected.value = true
        
        // 发送心跳
        startHeartbeat()
        
        // 清除重连定时器
        if (reconnectTimer) {
          clearTimeout(reconnectTimer)
          reconnectTimer = null
        }
      }

      ws.onmessage = (event) => {
        try {
          const updateEvent: LifeEntityUpdateEvent = JSON.parse(event.data)
          handleUpdateEvent(updateEvent)
        } catch (error) {
          console.error('Failed to parse WebSocket message:', error)
        }
      }

      ws.onclose = () => {
        console.log('Life entity WebSocket disconnected')
        isConnected.value = false
        stopHeartbeat()
        
        // 尝试重连
        scheduleReconnect()
      }

      ws.onerror = (error) => {
        console.error('Life entity WebSocket error:', error)
        isConnected.value = false
      }

    } catch (error) {
      console.error('Failed to connect to WebSocket:', error)
      scheduleReconnect()
    }
  }

  // 断开连接
  const disconnect = () => {
    if (ws) {
      ws.close()
      ws = null
    }
    
    if (reconnectTimer) {
      clearTimeout(reconnectTimer)
      reconnectTimer = null
    }
    
    stopHeartbeat()
    isConnected.value = false
  }

  // 处理更新事件
  const handleUpdateEvent = (event: LifeEntityUpdateEvent) => {
    lastUpdate.value = new Date()
    updateEvents.value.unshift(event)
    
    // 保持最近100个事件
    if (updateEvents.value.length > 100) {
      updateEvents.value = updateEvents.value.slice(0, 100)
    }

    // 触发监听器
    const eventListeners = listeners.get(event.type) || []
    eventListeners.forEach(listener => {
      try {
        listener(event)
      } catch (error) {
        console.error('Error in event listener:', error)
      }
    })

    // 显示通知
    showUpdateNotification(event)
  }

  // 显示更新通知
  const showUpdateNotification = (event: LifeEntityUpdateEvent) => {
    switch (event.type) {
      case 'ENTITY_CREATED':
        message.success(`新生命体已创建: ${event.entity?.name}`)
        break
      case 'ENTITY_UPDATED':
        message.info(`生命体已更新: ${event.entity?.name}`)
        break
      case 'ENTITY_DELETED':
        message.warning(`生命体已删除: ${event.entityId}`)
        break
      case 'STATUS_CHANGED':
        message.info(`生命体状态变更: ${event.oldStatus} → ${event.newStatus}`)
        break
    }
  }

  // 安排重连
  const scheduleReconnect = () => {
    if (reconnectTimer) return
    
    reconnectTimer = setTimeout(() => {
      console.log('Attempting to reconnect WebSocket...')
      connect()
    }, 5000) // 5秒后重连
  }

  // 开始心跳
  const startHeartbeat = () => {
    heartbeatTimer = setInterval(() => {
      if (ws && ws.readyState === WebSocket.OPEN) {
        ws.send(JSON.stringify({ type: 'PING' }))
      }
    }, 30000) // 30秒心跳
  }

  // 停止心跳
  const stopHeartbeat = () => {
    if (heartbeatTimer) {
      clearInterval(heartbeatTimer)
      heartbeatTimer = null
    }
  }

  // 添加事件监听器
  const addEventListener = (eventType: string, listener: (event: LifeEntityUpdateEvent) => void) => {
    if (!listeners.has(eventType)) {
      listeners.set(eventType, [])
    }
    listeners.get(eventType)!.push(listener)
  }

  // 移除事件监听器
  const removeEventListener = (eventType: string, listener: (event: LifeEntityUpdateEvent) => void) => {
    const eventListeners = listeners.get(eventType)
    if (eventListeners) {
      const index = eventListeners.indexOf(listener)
      if (index > -1) {
        eventListeners.splice(index, 1)
      }
    }
  }

  // 获取最近的更新事件
  const getRecentEvents = (count: number = 10) => {
    return updateEvents.value.slice(0, count)
  }

  // 清除事件历史
  const clearEvents = () => {
    updateEvents.value = []
  }

  onMounted(() => {
    connect()
  })

  onUnmounted(() => {
    disconnect()
  })

  return {
    isConnected,
    lastUpdate,
    updateEvents,
    connect,
    disconnect,
    addEventListener,
    removeEventListener,
    getRecentEvents,
    clearEvents,
  }
}